<template>


<div>
    <h1>1---新增学生</h1>


    <p>姓名：<input type="text" v-model="name"></p>
    <p>年龄：<input type="text" v-model="age"></p>

    <p>照片：<input type="file" id='img'></p>

    <p>老师：
        <select name="" v-model="teacher">
            <option :value="tea.id"  v-for='(tea, index) in teacher_li' :key="index"> {{  tea.name}} </option>
        </select>
    </p>

    <p><button @click="add_stu">新增</button></p>


</div>


</template>

<script>
import axios from 'axios'

export default {

    // 1. 数据
    data() {
        return {
            name:'',
            age: '',
            teacher:'',
            teacher_li: []
        }
    },

    // 2. 新增学生
    methods: {
        add_stu(){

            // 2.1 准备表单数据---图片等文件需要放到FormData当中
            let fdata = new FormData()
            fdata.append('name', this.name)
            fdata.append('age', this.age)
            fdata.append('img', document.getElementById('img').files[0])
            fdata.append('teacher', this.teacher)

            // console.log(this.teacher, '-------------------')

            axios({
                url: 'http://127.0.0.1:8000/demo/student/',
                method: 'post',
                data: fdata
            }).then(res => {
                console.log(res.data)
                
                if (res.data.code==200) {
                    this.$router.push('/')
                }else{
                    alert(res.data.msg)
                }

            })
        }
    },

    // 3. 钩子函数
    created() {
        axios({
            url: 'http://127.0.0.1:8000/demo/teacher/',
            method: 'get'
        }).then(res => {
            // console.log(res.data)
            this.teacher_li = res.data.teacher_li
            console.log(this.teacher_li)
        })

    },

}
</script>

<style>

</style>